<?php   

//  retrieve.php
//  Memento 3.0
//
//  Created by Christopher Burrows on 10-07-29
//  Copyright 2010 Team Memento. All rights reserved.
//
//    Description:
//  Returns a jpg or caf file to the client, or outputs
//  an XML list of all the memories associated with a
//  colleciton id.
//
//  10-08-02: Use 500 internal server errors instead of stdout for easier client trapping when expecting attachments (C. Maddocks)
//  10-07-29: File created. (C. Burrows)
//
//  HTML POST Fields:
//  'session_token' (string)
//  'memory_id'     (int)
//  'component'     (int 0-2)
//
//  OUTPUT:
//  Line 1: False if validation fails, or file does not exist,
//          otherwise the file is echoed to the client.

include ($_SERVER['DOCUMENT_ROOT'].'/functions.php');
connect_to_database();

$session_token = $_REQUEST ['session_token'];
$memory_id = $_REQUEST ['memory_id'];
$component = $_REQUEST ['component'];

if (!validate_session_token($session_token)) {

    //echo '0'.PHP_EOL;
    header ("HTTP/1.1 500 Internal Server Error");

} else {      

    // Get the collection_id
    $result = mysql_query("SELECT * FROM sessions WHERE
            session_token='$session_token'");
    $row = mysql_fetch_array($result);
    $collection_id = $row['collection_id'];
    
    $downloaddir = '/home/mementof/memento.freehostingcloud.com/upload/'.$collection_id;
    $downloadfile = '/'.$memory_id;
    
    if ($component == '0') {
        
        // Client is requesting XML metadata for a single Memory
        xml_list($collection_id, $memory_id);
        
    } else {
        
        // Client is requesting a file
        
        if ($component == '1') {
            $downloadfile = $downloadfile.'.jpg';
        } else {
            $downloadfile = $downloadfile.'.caf';
        }
        
        if (!is_file($downloaddir.$downloadfile)) {
            header ("HTTP/1.1 500 Internal Server Error");
            //echo $downloaddir.$downloadfile.' is not a file.';
            //echo '0'.PHP_EOL;
        
        } else {
                
            header("Location: http://memento.freehostingcloud.com/retrieve_file.php?session=$session_token&collection=$collection_id&id=$memory_id&action=$component");
            
        }
        
    }
    
}

?>